package main.java.org.result;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import main.java.Exam.pojo.Entity.TestQuestion;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@MappedTypes({List.class}) // 或更精准：@MappedTypes({List.class}) + 确保处理 TestQuestion 泛型
@MappedJdbcTypes(value = JdbcType.VARCHAR, includeNullJdbcType = true) // 包含 null 类型处理
public class TestQuestionListTypeHandler extends BaseTypeHandler<List<TestQuestion>> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 序列化（存储时已正常工作，无需修改）
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<TestQuestion> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String json = objectMapper.writeValueAsString(parameter);
            ps.setString(i, json);
        } catch (JsonProcessingException e) {
            throw new SQLException("Failed to serialize List<TestQuestion> to JSON", e);
        }
    }

    // 反序列化（查询时核心逻辑，确保无错误）
    @Override
    public List<TestQuestion> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseJson(rs.getString(columnName));
    }

    @Override
    public List<TestQuestion> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseJson(rs.getString(columnIndex));
    }

    @Override
    public List<TestQuestion> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseJson(cs.getString(columnIndex));
    }

    // 解析 JSON 为 List<TestQuestion>，确保泛型正确
    private List<TestQuestion> parseJson(String json) {
        if (json == null || json.trim().isEmpty() || "null".equals(json)) {
            return new ArrayList<>(); // 空值返回空列表，避免 null
        }
        try {
            // 关键：指定泛型类型，避免解析为 LinkedHashMap
            return objectMapper.readValue(
                    json,
                    objectMapper.getTypeFactory().constructCollectionType(List.class, TestQuestion.class)
            );
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to deserialize JSON to List<TestQuestion>", e);
        }
    }
}